package com.shchuangzhi.smartguard.core.command;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shchuangzhi.smartguard.core.Consts;
import com.shchuangzhi.smartguard.core.NotifyMessage;
import com.shchuangzhi.smartguard.core.School;

import java.io.InputStream;


/**
 * Created by j_hu on 5/9/17.
 */

public class SyncSchoolHandler extends SyncMetaCommandRespHandler {
    public SyncSchoolHandler(SyncMetaCommand cmd) {
        super("school.sync", cmd);
    }

    @Override
    public boolean handle(InputStream input) {
        boolean handleOk = false;
        try {
            Gson gson = new Gson();
            SyncMetaCommandRS<SyncSchoolRS> syncRS = (SyncMetaCommandRS<SyncSchoolRS>)gson.fromJson(
                    getString(input),
                    new TypeToken<SyncMetaCommandRS<SyncSchoolRS>>(){}.getType());

            if (syncRS != null && syncRS.getData() != null) {
                getCommand().notify(NotifyMessage.info(Consts.INFO_SYNC_SCHOOL, Consts.NOTIFY_DATA_SYNC, Consts.NOTIFY_DATA_SYC_VIEW_LIST));
                School school = new School(getCommand().getDbHelper());
                school.setId(syncRS.getData().getId());
                school.setName(syncRS.getData().getName());
                if (school.reset()) {
                    getCommand().getDbHelper().getSyncRecord().update(getName(), syncRS.getLastMetaUpdateTime());
                    getCommand().notify(NotifyMessage.info(Consts.INFO_SYNC_SCHOOL_OK, Consts.NOTIFY_DATA_SYNC, Consts.NOTIFY_DATA_SYC_VIEW_LIST));
                    getCommand().notify(NotifyMessage.wrap(school.getName(), Consts.NOTIFY_SCHOOL_CHANGED));
                    handleOk = true;
                } else {
                    getCommand().notify(NotifyMessage.info(Consts.INFO_SYNC_SCHOOL_FAIL, Consts.NOTIFY_DATA_SYNC, Consts.NOTIFY_DATA_SYC_VIEW_LIST));
                }
            }
        }catch(Exception e) {
            getCommand().raiseError(e);
        }
        return handleOk;
    }

    public class SyncSchoolRS {
        private String id;
        private String name;

        public String getId() {
            return id;
        }

        public String getName() {
            return name;
        }
    }
}
